<script>
import _ from 'lodash'

export default {
  name: 'treeTable',
  props: ['config', 'data', 'filter'],
  methods: {
    filterTree(one) {
      if (!this.filter) {
        return true
      } else {
        return this.filter(one) || _.some(one.children || [], one => this.filterTree(one))
      }
    }
  },
  render(h) {
    let colgroup = <colgroup>
      { _.map(this.config, one => (<col style={ 'width:' + one.width }></col>)) }
    </colgroup>
    const generateTr = (item, level) => {
      return <tr>{ this.config.map((configOne, index) => {
        let style = {}
        let content = []
        let title
        if (index === 0) {
          style.paddingLeft = 12 + level * 32 + 'px'
          let iconClass = item.collapse ? '加号' : '减号'
          if (item.children && item.children.length) {
            content.push(<svg-icon icon-class={ iconClass } style="cursor: pointer;color:#66b1ff"
                                   nativeOnClick={ () => {
                                     this.$set(item, 'collapse', !item.collapse)
                                   } }></svg-icon>)
          } else {

          }
        }

        if (configOne.prop) {
          if (configOne.prop.indexOf('.') > -1) {
            content.push(_.at(item.data, configOne.prop)[0])
            return <td title={ title } style={ style }>{ content }</td>
          }
          content.push(item.data[configOne.prop])
          return <td title={ title } style={ style }>{ content }</td>
        }
        if (configOne.render) {
          content.push(configOne.render(h, item))
          return <td style={ style }>{ content }</td>
        }
        return <td>{ content }</td>
      }) }</tr>
    }
    const generateTrs = (data, level) => {
      return _.flatten(data.map(one => {
        if (this.filterTree(one)) {
          let tr = generateTr(one, level)
          if (one.collapse || (!one.children)) {
            return [tr]
          } else {
            return [tr, ...generateTrs(one.children, level + 1)]
          }
        } else {
          return []
        }
      }))
    }
    return <table class="tree-table" style="table-layout:fixed;width:100%">
      { colgroup }
      <thead>
      <tr>
        { _.map(this.config, one => <th>{ one.label }</th>) }
      </tr>
      </thead>
      <tbody>
      { generateTrs(this.data, 0) }
      </tbody>
    </table>
  }
}

</script>

<style scoped lang="scss">
  table.tree-table {
    border-collapse: collapse;
    td, th {
      padding: 12px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    td {
      border: #ebeef5 1px solid;
      border-collapse: collapse;
      color: #606266;
    }

    th {
      text-align: left;
      color: #909399 !important;
      border: #ebeef5 1px solid;
    }
  }

</style>
